package cn.edu.cdtu.healthserver.utils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

import cn.edu.cdtu.healthserver.domain.NewsFromInternet;
//XML文件解析工具，（解析XML文件里的数据）
public class XmlUtil 
{
	//通过URL获得XML文件，并解析文件，获得的结果存入List列表中。
	public List<?> getXmlInformation(String path, URL url) 
	{
		List<?> xmlInformation = new ArrayList<Object>();
		try 
		{
			SAXReader saxReader = new SAXReader();
			Document document = saxReader.read(url);
			xmlInformation = document.selectNodes(path);
		} 
		catch (DocumentException e) 
		{
			e.printStackTrace();
		}
		//返回包含封装在Object对象中的List列表。
		return xmlInformation;
	}
	
	//生成XML的方法。
	public void generateXML(List<NewsFromInternet> internetNewsList,String savePath)
	{
		RandomAccessFile newsXmlFile = null;
		
		if(StringUtils.isEmpty(savePath) || StringUtils.isBlank(savePath))
		{
			System.out.println("无存储位置,generateXML方法直接返回");
			return;
		}
		
		File directory = new File(savePath);
		//若指定存储目录不存在，则创建目录
		if(!directory.isDirectory())
		{
			directory.mkdirs();
		}
		
		try 
		{
			newsXmlFile=new RandomAccessFile(savePath + "news.xml", "rw");
			//写入标准XML头,\r回车使光标移到行首,\n换行使光标移到下一行，两个加起来等于一个enter键
			newsXmlFile.write(("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + "\r\n").getBytes("utf-8"));
			//根结点
			newsXmlFile.write(("<root>"+"\r\n").getBytes("utf-8"));
		}
		catch (FileNotFoundException e) 
		{
			e.printStackTrace();
		}
		catch (UnsupportedEncodingException e) 
		{
			e.printStackTrace();
		}
		catch (IOException e) 
		{
			e.printStackTrace();
		}
		
		for(NewsFromInternet news:internetNewsList)
		{
			try 
			{
				newsXmlFile.write(("<news>"+"\r\n").toString().getBytes("utf-8"));
				newsXmlFile.write(("<title>"+news.getTitle()+"</title>"+"\r\n").getBytes("utf-8"));
				newsXmlFile.write(("<description>"+news.getDescription()+"</description>"+"\r\n").getBytes("utf-8"));
				newsXmlFile.write(("<pubDate>"+news.getPubDate()+"</pubDate>"+"\r\n").getBytes("utf-8"));
				newsXmlFile.write(("<link>"+news.getLink()+"</link>"+"\r\n").getBytes("utf-8"));
				newsXmlFile.write(("</news> \r\n").getBytes("utf-8"));
			}
			catch (IOException e) 
			{
	            e.printStackTrace();
	        } 
		}
		
		try 
		{
			newsXmlFile.write("</root> \r\n".getBytes("utf-8"));
		} 
		catch (UnsupportedEncodingException e) 
		{
			e.printStackTrace();
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}
}
